<template>
  <view class="form-container">
    <uni-forms ref="formRef" :model="formData" :rules="rules" label-width="120rpx">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">基本信息</view>
        
        <uni-forms-item name="name" label="活动名称" required>
          <uni-easyinput 
            v-model="formData.name" 
            placeholder="请输入活动名称"
            maxlength="100"
          />
        </uni-forms-item>

        <uni-forms-item name="description" label="活动描述" required>
          <uni-easyinput 
            v-model="formData.description" 
            type="textarea"
            placeholder="请输入活动描述"
            maxlength="500"
            :auto-height="true"
          />
        </uni-forms-item>

        <uni-forms-item name="image" label="活动图片">
          <view class="image-upload">
            <view v-if="formData.image" class="image-preview" @click="previewImage">
              <image :src="formData.image" mode="aspectFill" />
              <view class="image-remove" @click.stop="removeImage">
                <uni-icons type="close" size="16" color="#fff" />
              </view>
            </view>
            <view v-else class="image-placeholder" @click="chooseImage">
              <uni-icons type="camera" size="32" color="#999" />
              <text class="placeholder-text">点击上传图片</text>
            </view>
          </view>
        </uni-forms-item>
      </view>

      <!-- 价格设置 -->
      <view class="form-section">
        <view class="section-title">价格设置</view>
        
        <view class="price-row">
          <uni-forms-item name="original_price" label="原价" required>
            <uni-number-box 
              v-model="originalPriceYuan" 
              :min="0" 
              :step="0.01"
              @change="handleOriginalPriceChange"
            />
          </uni-forms-item>
          
          <uni-forms-item name="group_price" label="团购价" required>
            <uni-number-box 
              v-model="groupPriceYuan" 
              :min="0" 
              :step="0.01"
              @change="handleGroupPriceChange"
            />
          </uni-forms-item>
        </view>

        <uni-forms-item name="deductible_hours" label="可抵扣时长" required>
          <uni-number-box 
            v-model="formData.deductible_hours" 
            :min="0" 
            :step="0.5"
          />
          <text class="unit-text">小时</text>
        </uni-forms-item>
      </view>

      <!-- 活动时间 -->
      <view class="form-section">
        <view class="section-title">活动时间</view>
        
        <uni-forms-item name="start_time" label="开始时间" required>
          <uni-datetime-picker 
            v-model="startTimeStr"
            type="datetime"
            @change="handleStartTimeChange"
          />
        </uni-forms-item>

        <uni-forms-item name="end_time" label="结束时间" required>
          <uni-datetime-picker 
            v-model="endTimeStr"
            type="datetime"
            @change="handleEndTimeChange"
          />
        </uni-forms-item>
      </view>

      <!-- 参团设置 -->
      <view class="form-section">
        <view class="section-title">参团设置</view>
        
        <view class="member-row">
          <uni-forms-item name="min_members" label="最少人数" required>
            <uni-number-box 
              v-model="formData.min_members" 
              :min="2" 
              :max="100"
            />
          </uni-forms-item>
          
          <uni-forms-item name="max_members" label="最多人数">
            <uni-number-box 
              v-model="formData.max_members" 
              :min="0" 
              :max="100"
            />
            <text class="hint-text">0表示不限</text>
          </uni-forms-item>
        </view>

        <uni-forms-item name="limit_per_member" label="每人限购" required>
          <uni-number-box 
            v-model="formData.limit_per_member" 
            :min="1" 
            :max="10"
          />
          <text class="unit-text">份</text>
        </uni-forms-item>
      </view>

      <!-- 适用范围 -->
      <view class="form-section">
        <view class="section-title">适用范围</view>
        
        <uni-forms-item name="applicable_stores" label="适用门店">
          <uni-data-checkbox 
            v-model="formData.applicable_stores"
            :localdata="storeOptions"
            multiple
            @change="handleStoreChange"
          />
        </uni-forms-item>

        <uni-forms-item name="applicable_venues" label="适用场地" v-if="venueOptions.length > 0">
          <uni-data-checkbox 
            v-model="formData.applicable_venues"
            :localdata="venueOptions"
            multiple
          />
        </uni-forms-item>
      </view>

      <!-- 可用时间 -->
      <view class="form-section">
        <view class="section-title">可用时间</view>
        
        <uni-forms-item name="available_weekdays" label="可用星期">
          <uni-data-checkbox 
            v-model="formData.available_weekdays"
            :localdata="weekdayOptions"
            multiple
          />
        </uni-forms-item>

        <uni-forms-item name="available_times" label="可用时段">
          <view class="time-slots">
            <view 
              v-for="(timeSlot, index) in formData.available_times" 
              :key="index"
              class="time-slot-item"
            >
              <uni-datetime-picker 
                v-model="timeSlot.start_time"
                type="time"
                @change="(val: string) => handleTimeSlotChange(index, 'start_time', val)"
              />
              <text class="time-separator">-</text>
              <uni-datetime-picker 
                v-model="timeSlot.end_time"
                type="time"
                @change="(val: string) => handleTimeSlotChange(index, 'end_time', val)"
              />
              <button class="remove-btn" @click="removeTimeSlot(index)">
                <uni-icons type="trash" size="16" />
              </button>
            </view>
            <button class="add-time-btn" @click="addTimeSlot">
              <uni-icons type="plus" size="16" />
              <text>添加时段</text>
            </button>
          </view>
        </uni-forms-item>
      </view>

      <!-- 其他设置 -->
      <view class="form-section">
        <view class="section-title">其他设置</view>
        
        <uni-forms-item name="status" label="活动状态" required>
          <uni-data-checkbox 
            v-model="formData.status"
            :localdata="statusOptions"
          />
        </uni-forms-item>

        <uni-forms-item name="support_balance" label="支持余额支付">
          <switch 
            :checked="formData.support_balance" 
            @change="handleSupportBalanceChange"
          />
        </uni-forms-item>

        <uni-forms-item name="sort_order" label="排序值" required>
          <uni-number-box 
            v-model="formData.sort_order" 
            :min="0" 
            :max="9999"
          />
          <text class="hint-text">数值越小越靠前</text>
        </uni-forms-item>
      </view>
    </uni-forms>

    <!-- 底部操作按钮 -->
    <view class="form-actions">
      <button class="action-btn secondary" @click="handleCancel">取消</button>
      <button class="action-btn primary" @click="handleSubmit" :loading="loading">保存</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { commonApi } from '@/api/groupbuy';
import type { Activity } from '@/types/groupbuy';

// Props
interface Props {
  initialValues?: Activity;
  loading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
});

// Emits
const emit = defineEmits<{
  submit: [data: Activity];
  cancel: [];
}>();

// 表单引用
const formRef = ref();

// 表单数据
const formData = reactive<Activity>({
  id: 0,
  name: '',
  description: '',
  image: '',
  original_price: 0,
  group_price: 0,
  start_time: Math.floor(Date.now() / 1000),
  end_time: Math.floor(Date.now() / 1000) + 7 * 24 * 3600,
  min_members: 2,
  max_members: 0,
  limit_per_member: 1,
  support_balance: false,
  deductible_hours: 1,
  applicable_stores: [],
  applicable_venues: [],
  available_weekdays: [],
  available_times: [],
  sort_order: 0,
  status: 1,
});

// 价格相关（以元为单位显示）
const originalPriceYuan = ref(0);
const groupPriceYuan = ref(0);

// 时间相关
const startTimeStr = ref('');
const endTimeStr = ref('');

// 选项数据
const storeList = ref<any[]>([]);
const venueList = ref<any[]>([]);

// 计算属性
const storeOptions = computed(() => {
  return storeList.value.map(store => ({
    value: store.id,
    text: store.name,
  }));
});

const venueOptions = computed(() => {
  const selectedStoreIds = formData.applicable_stores;
  if (!selectedStoreIds.length) return [];
  
  return venueList.value
    .filter(venue => selectedStoreIds.includes(venue.store_id))
    .map(venue => ({
      value: venue.id,
      text: venue.name,
    }));
});

const weekdayOptions = [
  { value: 1, text: '周一' },
  { value: 2, text: '周二' },
  { value: 3, text: '周三' },
  { value: 4, text: '周四' },
  { value: 5, text: '周五' },
  { value: 6, text: '周六' },
  { value: 0, text: '周日' },
];

const statusOptions = [
  { value: 1, text: '启用' },
  { value: 0, text: '禁用' },
];

// 表单验证规则
const rules = {
  name: {
    rules: [
      { required: true, errorMessage: '请输入活动名称' },
      { minLength: 1, maxLength: 100, errorMessage: '活动名称长度为1-100个字符' },
    ],
  },
  description: {
    rules: [
      { required: true, errorMessage: '请输入活动描述' },
      { minLength: 1, maxLength: 500, errorMessage: '活动描述长度为1-500个字符' },
    ],
  },
  original_price: {
    rules: [
      { required: true, errorMessage: '请输入原价' },
    ],
  },
  group_price: {
    rules: [
      { required: true, errorMessage: '请输入团购价' },
    ],
  },
  deductible_hours: {
    rules: [
      { required: true, errorMessage: '请输入可抵扣时长' },
    ],
  },
  start_time: {
    rules: [
      { required: true, errorMessage: '请选择开始时间' },
    ],
  },
  end_time: {
    rules: [
      { required: true, errorMessage: '请选择结束时间' },
    ],
  },
  min_members: {
    rules: [
      { required: true, errorMessage: '请输入最少参团人数' },
    ],
  },
  limit_per_member: {
    rules: [
      { required: true, errorMessage: '请输入每人限购数量' },
    ],
  },
  status: {
    rules: [
      { required: true, errorMessage: '请选择活动状态' },
    ],
  },
  sort_order: {
    rules: [
      { required: true, errorMessage: '请输入排序值' },
    ],
  },
};

// 监听初始值变化
watch(() => props.initialValues, (newVal) => {
  if (newVal) {
    Object.assign(formData, newVal);
    originalPriceYuan.value = newVal.original_price / 100;
    groupPriceYuan.value = newVal.group_price / 100;
    startTimeStr.value = formatTimestamp(newVal.start_time);
    endTimeStr.value = formatTimestamp(newVal.end_time);
  }
}, { immediate: true, deep: true });

// 格式化时间戳为字符串
const formatTimestamp = (timestamp: number) => {
  const date = new Date(timestamp * 1000);
  return date.toISOString().slice(0, 16);
};

// 处理价格变化
const handleOriginalPriceChange = (value: number) => {
  formData.original_price = Math.round(value * 100);
};

const handleGroupPriceChange = (value: number) => {
  formData.group_price = Math.round(value * 100);
};

// 处理时间变化
const handleStartTimeChange = (value: string) => {
  formData.start_time = Math.floor(new Date(value).getTime() / 1000);
};

const handleEndTimeChange = (value: string) => {
  formData.end_time = Math.floor(new Date(value).getTime() / 1000);
};

// 处理门店变化
const handleStoreChange = () => {
  // 清空已选场地
  formData.applicable_venues = [];
};

// 处理余额支付开关
const handleSupportBalanceChange = (e: any) => {
  formData.support_balance = e.detail.value;
};

// 处理时段变化
const handleTimeSlotChange = (index: number, field: 'start_time' | 'end_time', value: string) => {
  formData.available_times[index][field] = value;
};

// 添加时段
const addTimeSlot = () => {
  formData.available_times.push({
    start_time: '09:00',
    end_time: '18:00',
  });
};

// 删除时段
const removeTimeSlot = (index: number) => {
  formData.available_times.splice(index, 1);
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0];
      try {
        // 这里应该调用上传接口
        // const uploadRes = await commonApi.uploadImage(tempFilePath);
        // formData.image = uploadRes.url;
        
        // 临时使用本地路径
        formData.image = tempFilePath;
        uni.showToast({
          title: '图片上传成功',
          icon: 'success',
        });
      } catch (error) {
        console.error('图片上传失败:', error);
        uni.showToast({
          title: '图片上传失败',
          icon: 'none',
        });
      }
    },
  });
};

// 预览图片
const previewImage = () => {
  if (formData.image) {
    uni.previewImage({
      urls: [formData.image],
    });
  }
};

// 删除图片
const removeImage = () => {
  formData.image = '';
};

// 加载门店列表
const loadStoreList = async () => {
  try {
    const res = await commonApi.getStores();
    if (res?.list) {
      storeList.value = res.list;
    }
  } catch (error) {
    console.error('加载门店列表失败:', error);
  }
};

// 加载场地列表
const loadVenueList = async () => {
  try {
    const res = await commonApi.getVenues();
    if (res?.list) {
      venueList.value = res.list;
    }
  } catch (error) {
    console.error('加载场地列表失败:', error);
  }
};

// 处理取消
const handleCancel = () => {
  emit('cancel');
};

// 处理提交
const handleSubmit = async () => {
  try {
    const valid = await formRef.value.validate();
    if (valid) {
      // 验证时间逻辑
      if (formData.end_time <= formData.start_time) {
        uni.showToast({
          title: '结束时间必须大于开始时间',
          icon: 'none',
        });
        return;
      }

      // 验证团购价不能大于原价
      if (formData.group_price >= formData.original_price) {
        uni.showToast({
          title: '团购价必须小于原价',
          icon: 'none',
        });
        return;
      }

      // 验证成团人数
      if (formData.max_members > 0 && formData.max_members < formData.min_members) {
        uni.showToast({
          title: '最大参团人数不能小于最少参团人数',
          icon: 'none',
        });
        return;
      }

      emit('submit', { ...formData });
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

// 页面加载
onMounted(() => {
  loadStoreList();
  loadVenueList();
});
</script>

<style lang="scss" scoped>
.form-container {
  padding: 24rpx;
}

.form-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.image-upload {
  .image-preview {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    border-radius: 12rpx;
    overflow: hidden;
    
    image {
      width: 100%;
      height: 100%;
    }
    
    .image-remove {
      position: absolute;
      top: 8rpx;
      right: 8rpx;
      width: 32rpx;
      height: 32rpx;
      background: rgba(0, 0, 0, 0.6);
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  .image-placeholder {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed #ddd;
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .placeholder-text {
      font-size: 24rpx;
      color: #999;
      margin-top: 12rpx;
    }
  }
}

.price-row, .member-row {
  display: flex;
  gap: 24rpx;
  
  .uni-forms-item {
    flex: 1;
  }
}

.unit-text, .hint-text {
  font-size: 24rpx;
  color: #999;
  margin-left: 12rpx;
}

.time-slots {
  .time-slot-item {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-bottom: 16rpx;
    
    .time-separator {
      font-size: 28rpx;
      color: #666;
    }
    
    .remove-btn {
      background: #FF4D4F;
      color: #fff;
      border: none;
      border-radius: 8rpx;
      padding: 8rpx;
      font-size: 24rpx;
    }
  }
  
  .add-time-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    width: 100%;
    padding: 24rpx;
    background: #f5f5f5;
    color: #666;
    border: none;
    border-radius: 12rpx;
    font-size: 26rpx;
  }
}

.form-actions {
  display: flex;
  gap: 24rpx;
  padding: 32rpx 0;
  
  .action-btn {
    flex: 1;
    padding: 24rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    border: none;
    
    &.secondary {
      background: #f5f5f5;
      color: #666;
    }
    
    &.primary {
      background: #1890FF;
      color: #fff;
    }
    
    &:active {
      opacity: 0.8;
    }
  }
}
</style>